import { defineStore } from "pinia"
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
import type { loginFromData, loginResponseData, userInfoResponseData } from '@/api/user/type'

import type { UserState } from "./type/type"
import { set_token, get_token, REMOVE_token } from "@/utils/tokenstorage"
//引入静态路由
import { constansRoute, asyncRoute, anyRoute } from "@/router/routers"
//深拷贝的库
//@ts-ignore
import cloneDeep from 'lodash/cloneDeep'
//引入路由
import router from "@/router"


//创建过滤当前用户需要展示的异步路由
function filterAsyncRoute(asyncRoute: any, routers: any) {
    return asyncRoute.filter((item: any) => {
        if (routers.includes(item.name)) {
            if (item.children && item.children.length > 0) {
                item.children = filterAsyncRoute(item.children, routers)
            }
            return true
        }
    })
}

//创建用户小仓库
let useUserStore = defineStore('User', {
    state: (): UserState => {
        return {
            token: get_token(),
            // 存储生成菜单的静态路由
            menuRouters: constansRoute,
            username: '',
            avatar: '',
            buttons: []
        }
    },
    //写异步写逻辑的地方     
    actions: {
        //用户登录的方法
        async userLogin(data: loginFromData) {
            let result: loginResponseData = await reqLogin(data)
            //如果登录成功存储token
            if (result.code == 200) {
                this.token = (result.data as string)
                //需要持久化存储token
                set_token((result.data as string))

                return 'ok'
            } else {
                return Promise.reject(new Error(result.data))
            }

        },
        //请求用户信息的方法
        async userInfo() {
            //获取用户存储于仓库中的头像和，姓名
            let result: userInfoResponseData = await reqUserInfo()
            if (result.code == 200) {
                this.username = result.data.name
                this.avatar = result.data.avatar
                this.buttons = result.data.buttons
                //由于路由一遍一遍的过滤会越来越少，所以要用深拷贝路由：cloneDeep
                let userAsyncroute = filterAsyncRoute(cloneDeep(asyncRoute), result.data.routes)
                //该用户包含的所有路由
                this.menuRouters = [...constansRoute, ...userAsyncroute, anyRoute];
                //目前路由器管理的只有常量路由，所以要给 用户追加过滤过的异步路由、任意路由
                [...userAsyncroute, anyRoute].forEach((item: any) => {
                    router.addRoute(item);
                });
                return 'ok'
            } else {
                return Promise.reject(new Error(result.message))
            }
        },
        async userLogout() {
            let result: any = await reqLogout();
            if (result.code == 200) {
                this.username = ''
                this.avatar = ''
                this.token = ''
                //清除本地存储token
                REMOVE_token();
                return 'ok'
            } else {
                return Promise.reject(new Error(result.message))
            }

        }
    },
    getters: {

    }
})
export default useUserStore